package com.example.bitintershipbbs.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import okhttp3.*;
import org.codehaus.plexus.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Component
public class ImageLocalProvider {
    /*令牌*/
    @Value("${image.token}")
    private String ACCESS_TOKEN;
    /*用户*/
    @Value("${image.url}")
    private String URL;


    public String upload(MultipartFile multipartFile) throws IOException {
        // 请求体封装
//        Map<String, Object> map = new HashMap<>(2);
//        map.put("file", multipartFile.getBytes());
//        map.put("token", ACCESS_TOKEN);
//
//        MediaType mediaType = MediaType.get("multipart/form-data");

        OkHttpClient client = new OkHttpClient().newBuilder().build();

        MediaType mediaType = MediaType.parse("text/plain");
        String fileName = multipartFile.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        File file = null;
        try {
            file = File.createTempFile(prefix, prefix);
            multipartFile.transferTo(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("file",fileName,
                        RequestBody.create(MediaType.parse("application/octet-stream"),
                                file))
                .addFormDataPart("token",ACCESS_TOKEN)
                .build();
        Request request = new Request.Builder()
                .url(URL)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String jsonResult = response.body().string();
            JSONObject jsonObject = JSON.parseObject(jsonResult);
            if (!jsonObject.get("code").equals(200)) {
                return null;
            }
            String murl = jsonObject.get("murl").toString();
            return murl;
        } catch (IOException e) {
        }
        return null;
    }
}
